//
//  MYGMyReportsNewViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/5/5.
//

import UIKit
import MJRefresh

class MYGMyReportsNewViewController: MYGBaseController {
    var dataSource = [MYGArticleModel]()
    var sortKey = 0//DESC降序/ ASC 升序
    var topModel = MYGArticleFromModel()
    var from = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的报道"
        let rightBar:UIBarButtonItem = UIBarButtonItem(customView: rightItemBtn)
        self.navigationItem.rightBarButtonItem = rightBar
        initUI()
        getList()
        getTopData()
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: Notification.Name("MYGMyReportsNewViewController_getList"), object: nil)
    }
    
    private func initUI(){
        view.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.top.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-100)
            make.height.equalTo(30)
        }
        view.addSubview(sortBtn)
        sortBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.size.equalTo(CGSize.init(width: 75, height: 30))
            make.centerY.equalTo(searchTextField.snp.centerY)
        }
        view.addSubview(topShowView)
        topShowView.snp.makeConstraints { make in
            make.top.equalTo(searchTextField.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(21)
        }
        view.addSubview(reportTable)
        reportTable.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(topShowView.snp.bottom)
        }
    }
    
    
    lazy var sortBtn: UIButton = {
        let control = UIButton()
        control.setTitleColor(UIColor.init(hexString: "#808080"), for: [])
        control.titleLabel?.font = .regular(12)
        control.setTitle("时间倒序", for: .normal)
        control.imageEdgeInsets = UIEdgeInsets(top: 0, left: 60, bottom: 0, right: 0)
        control.titleEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
        control.setImage(UIImage.init(named: "MYG_cloudDisk_arrow_down"), for: .normal)
        control.addTarget(self, action: #selector(tapSort), for: .touchUpInside)
        return control
    }()
    
    private lazy var rightItemBtn:UIButton = {
        let cont = UIButton()
        cont.setTitle("未确认报道", for: .normal)
        cont.titleLabel?.font = .regular(13)
        cont.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        cont.addTarget(self, action: #selector(tapSureReport), for: .touchUpInside)
        return cont
    }()
    
    private lazy var searchTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(142, 142, 147, 1)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 15
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Chat/search"))
            confer.text(" 搜索")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        tf.textAlignment = .center
        tf.addTarget(self, action: #selector(textValueChanged), for: .editingChanged)
        return tf
    }()
    
    lazy var topShowView: ReportTopScrollView = {
        let control = ReportTopScrollView()
        control.tapIndexCompletion = {[weak self] from in
            self?.from = from
            self?.getList()
        }
        return control
    }()
    
    private lazy var reportTable:UITableView = {
        let tab = UITableView(frame: CGRectZero, style: .plain)
        tab.delegate = self
        tab.backgroundColor = .clear
        tab.dataSource = self
        tab.register(cellWithClass: MYGMyReportsNewTableViewCell.self)
        tab.separatorStyle = .none
        tab.allowsMultipleSelectionDuringEditing = true
        return tab
    }()
    
    @objc func tapSureReport() {
        let parms = ["type": "2"]
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGArticleFromModel>.request(target: .articleNewsFromList(param: parms)) {[weak self] item in
            guard let `self` = self else {return}
            MYGLoading.hide()
            self.popup.dialog(with: true, bgColor: .black.withAlphaComponent(0.43)) {
                let actionSheet = Bundle.main.loadNibNamed("MYGSureReportAlert", owner: nil)?.first as! MYGSureReportAlert
                actionSheet.titleLB.text = "系统抓取到可能与您相关的\(item.count)篇报道，请选择是否前去确认"
                actionSheet.tapSureCallBack = {[weak self] in
                    self?.popup.dismissPopup()
                    let vc = MYGEditMyReportsVC()
                    self?.navigationController?.pushViewController(vc)
                }
                actionSheet.tapCancelCallBack = {[weak self] in
                    self?.popup.dismissPopup()
                }
                actionSheet.frame = CGRect.init(x: 0, y: 0, width: 340, height: 188)
                return actionSheet
            }
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
   @objc func reloadData() {
        getList()
        getTopData()
    }
    @objc func getList() {
        MYGLoading.show()
        let sort = self.sortKey == 0 ? "desc" : "asc"
        let parms = ["title":self.searchTextField.text ?? "", "sort":sort,"type": "1","from":from]
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGArticleModel>>.request(target: .articleList(param: parms)) { item in
            self.dataSource = item.list
            self.reportTable.reloadData()
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getTopData() {
        let parms = ["type": "1"]
        MYGNetwork<MYGMeAPI, MYGArticleFromModel>.request(target: .articleNewsFromList(param: parms)) {[weak self] item in
            self?.topModel = item
            self?.topShowView.configTopScrollView(item)
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func toDelete(_ ids:[String]) {
        let idstring = ids.joined(separator: ",")
        let parms = ["ids":idstring]
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGArticleModel>>.request(target: .deleteArticle(param: parms)) {[weak self] item in
            MYGLoading.hide()
            self?.getList()
            self?.getTopData()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc func tapSort() {
        YBPopupMenu.show(at: CGPoint(x: screenWidth - 25, y: navHeight + statusBarHeight + 43), titles: ["时间倒叙","时间升序"], icons: [], menuWidth: 85) { menu in
            menu?.delegate = self
            menu?.dismissOnSelected = true
            menu?.font = UIFont.regular(12)
            menu?.itemHeight = 30
            menu?.selectecIndex = self.sortKey
            menu?.selectedTextColor = UIColor.init(hexString: "#6389F1")
            menu?.separatorColor = .clear
            menu?.textColor = UIColor.init(hexString: "#C0BEBE")
        }
    }
    
    @objc func textValueChanged() {
        getList()
    }
}

extension MYGMyReportsNewViewController:YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        self.sortKey = index
        let title = self.sortKey == 0 ? "时间倒序": "时间升序"
        sortBtn.setTitle(title, for: .normal)
        getList()
    }
}

extension MYGMyReportsNewViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 127.5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGMyReportsNewTableViewCell", for: indexPath) as! MYGMyReportsNewTableViewCell
        cell.selectionStyle = .none
        let model = self.dataSource[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let unbind = UIContextualAction(style: .normal, title: "删除") {[weak self]
            (action, view, completionHandler) in
            guard let `self` = self else {return}
            let data = self.dataSource[indexPath.row]
            let ids = ["\(data.id)"]
            self.toDelete(ids)
            completionHandler(true)
        }
        unbind.backgroundColor = UIColor.init(hexString: "#FF0000")
        
        let configuration = UISwipeActionsConfiguration(actions: [unbind])
        return configuration
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.row]
        let vc = MYGMyReportDetailViewController()
        vc.id = "\(model.id)"
        self.navigationController?.pushViewController(vc)
    }
}

class ReportTopScrollView:UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(topScrollView)
        topScrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(screenWidth)
        }
    }
    
    var tapIndexCompletion:((String)->Void)?
    var dataSource = MYGArticleFromModel()
    
    var btns = [UIButton]()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var topScrollView:UIScrollView = {
        let control = UIScrollView()
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        return control
    }()
    
    func configTopScrollView(_ model: MYGArticleFromModel) {
        dataSource = model
        for sub in topScrollView.subviews {
            sub.removeFromSuperview()
        }
        let allBtn = getALLBtn()
        allBtn.tag = 200
        btns.append(allBtn)
        allBtn.addTarget(self, action: #selector(tapBtnAction(_:)), for: .touchUpInside)
        let text = "全部" + "(" + "\(model.count)" + ")"
        allBtn.setTitle(text, for: .normal)
        allBtn.frame = CGRect.init(x: 15, y: 0, width: 64, height: 21)
        topScrollView.addSubview(allBtn)
        var minX = 98.0
        var maxX = 0.0
        for(i,obj) in model.from_count.enumerated() {
            let btn = getNormalBtn()
            let text = obj.from +  "(" + "\(obj.count)" + ")"
            btn.setTitle(text, for: .normal)
            btn.tag = 100 + i
            btn.addTarget(self, action: #selector(tapBtnAction(_:)), for: .touchUpInside)
            let width = btn.sizeThatFits(CGSize.init(width: 200, height: 21)).width + 15
            btn.frame = CGRect.init(x: minX , y: 0, width: width, height: 21)
            minX = minX + width + 15
            maxX = CGRectGetMaxX(btn.frame)
            topScrollView.addSubview(btn)
            btns.append(btn)
        }
        topScrollView.contentSize = CGSize(width: maxX + 15 , height: 21)
    }
    
    func getNormalBtn()->UIButton{
        let btn = UIButton()
        btn.setTitleColor(UIColor.init(hexString: "#565656"), for: .normal)
        btn.titleLabel?.font = UIFont.regular(12)
        btn.backgroundColor = UIColor.init(hexString: "#f5f5f5")
        btn.layer.cornerRadius = 3
        btn.layer.masksToBounds = true
        return btn
    }
    
    @objc func tapBtnAction(_ sender:UIButton) {
        if sender.tag == 200 {
            if let c = tapIndexCompletion {
                c("")
            }
        }else {
            let title = dataSource.from_count[sender.tag - 100]
            if let c = tapIndexCompletion {
                c(title.from)
            }
        }
        for (_,btn) in btns.enumerated() {
            if btn.tag == sender.tag {
                btn.backgroundColor = UIColor.init(hexString: "#557EED")
                btn.setTitleColor(.white, for: .normal)
            }else {
                btn.setTitleColor(UIColor.init(hexString: "#565656"), for: .normal)
                btn.backgroundColor = UIColor.init(hexString: "#f5f5f5")
            }
        }
    }
    
    func getALLBtn()->UIButton{
        let btn = UIButton()
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .regular(12)
//        lb.textAlignment = .center
        btn.backgroundColor = UIColor.init(hexString: "#557EED")
        btn.layer.cornerRadius = 3
        btn.layer.masksToBounds = true
        return btn
    }
}
